#include "systemmain.h"
#include "constants.h"
#include "orderstatisticswidget.h"
#include <QApplication>
#include <QDateTime>
#include <QVBoxLayout>
#include <QListWidgetItem>
#include <QTabWidget>
#include <QScrollArea>
#include <QFont>
#include <QFontInfo>
#include <QGroupBox>
#include <QPushButton>

systemMain::systemMain(QWidget *parent)
    : QMainWindow(parent)
    , m_userManager(nullptr)
    , m_menuManager(nullptr)
    , m_orderManager(nullptr)
    , m_ratingManager(nullptr)
    , m_currentRole(LoginUI::UserRole::Customer)
    , m_currentUserId("")
    , m_centralWidget(nullptr)
    , m_mainLayout(nullptr)
    , m_mainSplitter(nullptr)
    , m_navigationList(nullptr)
    , m_navigationPanel(nullptr)
    , m_contentStack(nullptr)
    , m_fileMenu(nullptr)
    , m_viewMenu(nullptr)
    , m_helpMenu(nullptr)
    , m_logoutAction(nullptr)
    , m_exitAction(nullptr)
    , m_aboutAction(nullptr)
    , m_refreshAction(nullptr)
    , m_mainToolBar(nullptr)
    , m_userLabel(nullptr)
    , m_roleLabel(nullptr)
    , m_timeLabel(nullptr)
    , m_statusLabel(nullptr)
    , m_welcomePage(nullptr)
    , m_customerMenuPage(nullptr)
    , m_customerCartPage(nullptr)
    , m_userCenterPage(nullptr)
    , m_adminMenuPage(nullptr)
    , m_adminOrderPage(nullptr)
    , m_adminRatingPage(nullptr)
    , m_adminStatsPage(nullptr)
    , m_userInfoWidget(nullptr)
    , m_orderHistoryWidget(nullptr)
    , m_userSettingsWidget(nullptr)
    , m_ratingWidget(nullptr)
    , m_userManagementWidget(nullptr)
    , m_orderStatisticsWidget(nullptr)
    , m_statusTimer(nullptr)
    , m_currentModule(UIModule::Welcome)
    , m_customerTitleBar(nullptr)
    , m_titleLogoLabel(nullptr)
    , m_welcomeLabel(nullptr)
    , m_logoutButton(nullptr)
{
    // 获取业务管理器单例
    m_userManager = &UserManager::instance();
    m_menuManager = &MenuManager::instance();
    m_orderManager = &OrderManager::instance();
    m_ratingManager = &RatingManager::instance();
    m_reorderService = &ReorderService::instance();
    
    // 初始化业务管理器
    if (!m_userManager->initialize()) {
        QMessageBox::critical(this, "初始化错误", "用户管理器初始化失败");
    }
    if (!m_menuManager->initialize()) {
        QMessageBox::critical(this, "初始化错误", "菜单管理器初始化失败");
    }
    if (!m_orderManager->initialize()) {
        QMessageBox::critical(this, "初始化错误", "订单管理器初始化失败");
    }
    if (!m_ratingManager->initialize()) {
        QMessageBox::critical(this, "初始化错误", "评价管理器初始化失败");
    }
    if (!m_reorderService->initialize()) {
        QMessageBox::critical(this, "初始化错误", "重新下单服务初始化失败");
    }

    // 初始化状态定时器
    // 重新启用状态栏定时器，现在使用英文避免字体问题
    m_statusTimer = new QTimer(this);
    connect(m_statusTimer, &QTimer::timeout, this, &systemMain::refreshStatusBar);
    m_statusTimer->start(1000); // 每秒更新一次

    // 初始化界面
    initializeUI();
    
    // 设置字体，解决中文渲染问题
    setupFonts();
    
    // 应用样式
    applyStyleSheet();
    
    // 设置窗口属性
    setupWindow();
}

systemMain::~systemMain()
{
    // Qt会自动清理子对象
}

void systemMain::setCurrentUser(LoginUI::UserRole role, const QString &userId, const QString &username)
{
    m_currentRole = role;
    m_currentUserId = userId;
    m_currentUsername = username;
    
    // 设置顾客菜单页面的用户ID和MenuManager
    if (m_customerMenuPage) {
        m_customerMenuPage->setCurrentUserId(userId.toInt());
        // 在用户登录后再设置MenuManager，确保UI已完全初始化
        m_customerMenuPage->setMenuManager(m_menuManager);
    }
    
    // 设置购物车页面的用户ID和管理器
    if (m_customerCartPage) {
        m_customerCartPage->setCurrentUserId(userId.toInt());
        m_customerCartPage->setManagers(m_orderManager, m_menuManager);
    }
    
    // 设置管理员菜单页面的MenuManager
    if (m_adminMenuPage) {
        m_adminMenuPage->setMenuManager(m_menuManager);
    }
    
    // 设置用户管理组件的UserManager (管理员专用)
    if (m_userManagementWidget) {
        m_userManagementWidget->setUserManager(m_userManager);
    }
    
    // 设置用户个人中心组件的用户ID
    if (m_userInfoWidget) {
        // 只为普通用户设置用户信息，管理员可能没有用户记录
        if (role == LoginUI::UserRole::Customer) {
            // 延迟获取用户信息，避免在登录过程中引起死锁
            QTimer::singleShot(0, this, [this, userId]() {
                if (m_userInfoWidget && m_userManager) {
                    m_userInfoWidget->setUserInfo(m_userManager->getUserById(userId));
                }
            });
        }
    }
    // 暂时禁用这些组件的用户ID设置，避免潜在问题
    if (m_orderHistoryWidget && role == LoginUI::UserRole::Customer) {
        m_orderHistoryWidget->setUserId(userId);
    }
    if (m_ratingWidget && role == LoginUI::UserRole::Customer) {
        m_ratingWidget->setUserName(username);
    }
    // 已移除个人设置组件
    // if (m_userSettingsWidget) {
    //     m_userSettingsWidget->setUserId(userId);
    // }
    
    // 连接菜单页面和购物车页面的信号（使用Qt::UniqueConnection防止重复连接）
    if (m_customerMenuPage && m_customerCartPage) {
        // 菜单页面添加到购物车的信号连接到购物车页面
        connect(m_customerMenuPage, &CustomerMenuUI::addToCartRequested,
                m_customerCartPage, &CustomerCartUI::addItemToCart, Qt::UniqueConnection);
        
        // 菜单页面查看购物车的信号连接到主界面切换
        connect(m_customerMenuPage, &CustomerMenuUI::viewCartRequested,
                this, [this]() { switchToModule(UIModule::CustomerCart); }, Qt::UniqueConnection);
        
        // 购物车页面返回菜单的信号连接到主界面切换
        connect(m_customerCartPage, &CustomerCartUI::backToMenuRequested,
                this, [this]() { switchToModule(UIModule::CustomerMenu); }, Qt::UniqueConnection);
    }
    
    // 重新创建菜单栏和工具栏（根据用户角色）
    recreateMenuAndToolBar();
    
    // 更新界面状态
    updateUIState();

    // 管理员登录后默认展示欢迎页面
    if (role == LoginUI::UserRole::Admin) {
        switchToModule(UIModule::Welcome);
    }
}

void systemMain::switchToModule(UIModule module)
{
    m_currentModule = module;
    
    // 检查堆栈是否有效
    if (!m_contentStack) {
        return;
    }
    
    // 特殊处理：UserCenter模块根据角色智能路由
    if (module == UIModule::UserCenter) {
        if (m_currentRole == LoginUI::UserRole::Admin) {
            // 管理员访问UserCenter时显示用户管理界面
            showUserManagementInterface();
        } else {
            // 顾客访问UserCenter时显示个人中心界面
            showUserCenterInterface();
        }
        
        // 更新导航列表选中状态
        if (m_navigationList) {
            m_navigationList->setCurrentRow(static_cast<int>(module));
        }
        
        // 刷新状态栏
        refreshStatusBar();
        return;
    }
    
    // 处理其他模块
    int moduleIndex = static_cast<int>(module);
    int stackCount = m_contentStack->count();
    
    if (moduleIndex >= stackCount) {
        return;
    }
    
    m_contentStack->setCurrentIndex(moduleIndex);
    
    // 更新导航列表选中状态
    if (m_navigationList) {
        m_navigationList->setCurrentRow(static_cast<int>(module));
    }
    
    // 刷新状态栏
    refreshStatusBar();
}

void systemMain::handleLogout()
{
    int ret = QMessageBox::question(this, "确认登出", 
        "确定要登出当前用户吗？", 
        QMessageBox::Yes | QMessageBox::No, 
        QMessageBox::No);
    
    if (ret == QMessageBox::Yes) {
        // 清除当前用户的购物车数据
        if (m_customerCartPage) {
            m_customerCartPage->clearCartForUserSwitch();
        }
        
        // 关闭主窗口
        close();
        
        // 显示登录对话框
        LoginUI loginDialog;
        if (loginDialog.exec() == QDialog::Accepted) {
            // 获取新的登录信息
            setCurrentUser(loginDialog.getCurrentRole(), 
                          loginDialog.getLoggedInUserId(), 
                          loginDialog.getLoggedInUsername());
            show();
        } else {
            // 用户取消登录，退出应用
            QApplication::quit();
        }
    }
}

void systemMain::handleExit()
{
    int ret = QMessageBox::question(this, "确认退出", 
        "确定要退出餐厅点餐系统吗？", 
        QMessageBox::Yes | QMessageBox::No, 
        QMessageBox::No);
    
    if (ret == QMessageBox::Yes) {
        QApplication::quit();
    }
}

void systemMain::showAbout()
{
    QMessageBox::about(this, "关于餐厅点餐系统", 
        "<h3>餐厅点餐系统 v1.0</h3>"
        "<p>一个基于Qt的现代化餐厅点餐管理系统</p>"
        "<p><b>功能特性：</b></p>"
        "<ul>"
        "<li>用户管理和认证</li>"
        "<li>菜单管理和浏览</li>"
        "<li>订单管理和处理</li>"
        "<li>数据统计和分析</li>"
        "</ul>"
        "<p>Copyright © 2024 Restaurant Order System</p>");
}

void systemMain::refreshStatusBar()
{
    if (m_timeLabel) {
        m_timeLabel->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    }
    
    if (m_userLabel) {
        // 恢复中文显示，现在有字体保护
        m_userLabel->setText(QString("用户: %1").arg(m_currentUsername));
    }
    
    if (m_roleLabel) {
        // 恢复中文显示，现在有字体保护
        QString roleText = (m_currentRole == LoginUI::UserRole::Admin) ? "管理员" : "顾客";
        m_roleLabel->setText(QString("角色: %1").arg(roleText));
    }
    
    if (m_statusLabel) {
        // 恢复中文模块名，现在有字体保护
        QString moduleNames[] = {"欢迎页面", "菜单浏览", "购物车", "个人中心", "菜单管理", "订单管理", "用户评价", "数据统计"};
        int moduleIndex = static_cast<int>(m_currentModule);
        if (moduleIndex >= 0 && moduleIndex < 8) {
            QString moduleName = moduleNames[moduleIndex];
            // 根据角色调整索引3的显示名称
            if (moduleIndex == 3 && m_currentRole == LoginUI::UserRole::Admin) {
                moduleName = "用户管理";
            }
            m_statusLabel->setText(QString("当前模块: %1").arg(moduleName));
        } else {
            m_statusLabel->setText("当前模块: 未知");
        }
    }
}

void systemMain::onModuleSwitchRequested()
{
    // 处理模块切换请求 - 可以从工具栏按钮触发
}

void systemMain::onNavigationItemClicked()
{
    if (!m_navigationList) return;
    
    int row = m_navigationList->currentRow();
    if (row >= 0 && row < static_cast<int>(UIModule::AdminStats) + 1) {
        switchToModule(static_cast<UIModule>(row));
    }
}

void systemMain::initializeUI()
{
    createMenuBar();
    createToolBar();
    createStatusBar();
    createCentralWidget();
}

void systemMain::createMenuBar()
{
    // 管理员界面隐藏菜单栏，但保留快捷键功能
    if (m_currentRole == LoginUI::UserRole::Admin) {
        // 隐藏菜单栏
        menuBar()->hide();
        
        // 创建动作但不显示在菜单中，仅保留快捷键功能
        m_logoutAction = new QAction("登出", this);
        m_logoutAction->setShortcut(QKeySequence("Ctrl+L"));
        m_logoutAction->setStatusTip("登出当前用户");
        connect(m_logoutAction, &QAction::triggered, this, &systemMain::handleLogout);
        addAction(m_logoutAction);
        
        m_exitAction = new QAction("退出", this);
        m_exitAction->setShortcut(QKeySequence("Ctrl+Q"));
        m_exitAction->setStatusTip("退出应用程序");
        connect(m_exitAction, &QAction::triggered, this, &systemMain::handleExit);
        addAction(m_exitAction);
        
        m_refreshAction = new QAction("刷新", this);
        m_refreshAction->setShortcut(QKeySequence("F5"));
        m_refreshAction->setStatusTip("刷新当前页面");
        connect(m_refreshAction, &QAction::triggered, this, &systemMain::refreshStatusBar);
        addAction(m_refreshAction);
        
        m_aboutAction = new QAction("关于", this);
        m_aboutAction->setStatusTip("关于本系统");
        connect(m_aboutAction, &QAction::triggered, this, &systemMain::showAbout);
        addAction(m_aboutAction);
    } else {
        // 顾客界面隐藏菜单栏
        menuBar()->hide();
        
        // 为顾客界面创建美观的标题栏
        createCustomerTitleBar();
        
        // 仍然创建动作以保持快捷键功能，但不显示在菜单中
        m_logoutAction = new QAction("登出", this);
        m_logoutAction->setShortcut(QKeySequence("Ctrl+L"));
        connect(m_logoutAction, &QAction::triggered, this, &systemMain::handleLogout);
        addAction(m_logoutAction);
        
        m_exitAction = new QAction("退出", this);
        m_exitAction->setShortcut(QKeySequence("Ctrl+Q"));
        connect(m_exitAction, &QAction::triggered, this, &systemMain::handleExit);
        addAction(m_exitAction);
        
        m_refreshAction = new QAction("刷新", this);
        m_refreshAction->setShortcut(QKeySequence("F5"));
        connect(m_refreshAction, &QAction::triggered, this, &systemMain::refreshStatusBar);
        addAction(m_refreshAction);
    }
}

void systemMain::createToolBar()
{
    // 只为管理员显示工具栏
    if (m_currentRole == LoginUI::UserRole::Admin) {
        m_mainToolBar = addToolBar("主工具栏");
        m_mainToolBar->setMovable(false);
        
        // 添加主要操作到工具栏
        m_mainToolBar->addAction(m_logoutAction);
        m_mainToolBar->addSeparator();
        m_mainToolBar->addAction(m_exitAction);
    } else {
        // 顾客界面不显示工具栏
        // m_mainToolBar 保持为 nullptr
    }
}

void systemMain::createStatusBar()
{
    m_userLabel = new QLabel("用户: 未登录");
    m_roleLabel = new QLabel("角色: 未知");
    m_timeLabel = new QLabel();
    m_statusLabel = new QLabel("状态: 就绪");
    
    statusBar()->addWidget(m_userLabel);
    statusBar()->addWidget(m_roleLabel);
    statusBar()->addPermanentWidget(m_statusLabel);
    statusBar()->addPermanentWidget(m_timeLabel);
}

void systemMain::createCentralWidget()
{
    m_centralWidget = new QWidget(this);
    setCentralWidget(m_centralWidget);
    
    m_mainLayout = new QHBoxLayout(m_centralWidget);
    m_mainLayout->setContentsMargins(5, 5, 5, 5);
    m_mainLayout->setSpacing(5);
    
    // 创建分割器
    m_mainSplitter = new QSplitter(Qt::Horizontal, this);
    m_mainSplitter->setChildrenCollapsible(false); // 禁止子部件被完全折叠
    m_mainSplitter->setHandleWidth(0); // 完全隐藏分割条
    m_mainSplitter->setDisabled(false); // 确保分割器本身可用，但禁用调整
    m_mainLayout->addWidget(m_mainSplitter);
    
    // 创建导航面板和内容区域
    createNavigationPanel();
    
    // 创建内容堆栈
    m_contentStack = new QStackedWidget(this);
    
    // 创建各个页面
    m_welcomePage = createWelcomePage();
    
    // 创建顾客菜单浏览页面
    m_customerMenuPage = new CustomerMenuUI(this);
    // 延迟设置MenuManager，等UI完全初始化后再设置
    
    // 创建顾客购物车页面
    m_customerCartPage = new CustomerCartUI(this);
    
    // 创建用户个人中心页面
    m_userCenterPage = createUserCenterPage();
    
    // 创建用户管理组件 (管理员专用)
    m_userManagementWidget = new UserManagementWidget(this);
    m_userManagementWidget->hide();
    
    // 创建管理员菜单管理页面
    m_adminMenuPage = new AdminMenuWidget(this);
    
    // 创建订单管理界面
    m_adminOrderPage = new OrderManagementUI();
    m_adminOrderPage->initializeUI();
    
    // 创建评价查看界面
    m_adminRatingPage = new RatingViewWidget();
    m_adminRatingPage->setRatingManager(m_ratingManager);
    
    // 连接评价查看页面的状态消息信号
    connect(m_adminRatingPage, &RatingViewWidget::statusMessageChanged,
            this, [this](const QString &message, int timeout) {
                if (m_statusLabel) {
                    m_statusLabel->setText(message);
                    if (timeout > 0) {
                        QTimer::singleShot(timeout, this, [this]() {
                            if (m_statusLabel) {
                                m_statusLabel->setText("就绪");
                            }
                        });
                    }
                }
            });
    
    m_adminStatsPage = createAdminStatsPage();   // 创建管理员统计页面
    
    // 添加页面到堆栈
    m_contentStack->addWidget(m_welcomePage);        // 0
    m_contentStack->addWidget(m_customerMenuPage);   // 1
    m_contentStack->addWidget(m_customerCartPage);   // 2
    m_contentStack->addWidget(m_userCenterPage);     // 3
    m_contentStack->addWidget(m_adminMenuPage);      // 4
    m_contentStack->addWidget(m_adminOrderPage);     // 5
    m_contentStack->addWidget(m_adminRatingPage);    // 6
    m_contentStack->addWidget(m_adminStatsPage);     // 7
    
    // 添加到分割器
    m_mainSplitter->addWidget(m_navigationPanel);
    m_mainSplitter->addWidget(m_contentStack);
    
    // 设置分割器比例 - 固定导航面板宽度200px
    m_mainSplitter->setStretchFactor(0, 0); // 导航面板固定宽度
    m_mainSplitter->setStretchFactor(1, 1); // 内容区域自适应
    m_mainSplitter->setSizes({200, 820}); // 固定导航面板宽度为200px
    
    // 连接分割器信号，强制保持固定大小
    connect(m_mainSplitter, &QSplitter::splitterMoved, this, [this]() {
        // 每当分割器被移动时，强制重置为固定大小
        m_mainSplitter->setSizes({200, 820});
    });
}

void systemMain::createNavigationPanel()
{
    m_navigationPanel = new QWidget(this);
    m_navigationPanel->setFixedWidth(200); // 固定导航面板宽度，不允许调整
    m_navigationPanel->setMinimumHeight(600); // 设置最小高度，充分利用垂直空间
    
    QVBoxLayout *navLayout = new QVBoxLayout(m_navigationPanel);
    navLayout->setContentsMargins(12, 15, 12, 15); // 增加内边距
    navLayout->setSpacing(10); // 增加间距
    
    // 导航标题
    QLabel *navTitle = new QLabel("功能导航", this);
    navTitle->setAlignment(Qt::AlignCenter);
    navTitle->setObjectName("navTitle");
    
    // 导航列表
    m_navigationList = new QListWidget(this);
    m_navigationList->setObjectName("navigationList");
    
    // 设置导航列表的样式和间距，充分利用垂直空间
    m_navigationList->setSpacing(4); // 增加项目间距
    m_navigationList->setMinimumHeight(450); // 设置最小高度，确保充分利用空间
    
    // 添加导航项 - 初始化为默认值，稍后根据角色更新
    m_navigationList->addItem("* 欢迎页面");
    m_navigationList->addItem("* 菜单浏览");
    m_navigationList->addItem("* 购物车");
    m_navigationList->addItem("* 个人中心");  // 这一项会根据角色动态更新
    m_navigationList->addItem("* 菜单管理");
    m_navigationList->addItem("* 订单管理");
    m_navigationList->addItem("* 用户评价");
    m_navigationList->addItem("* 数据统计");
    
    // 默认选中欢迎页面（先设置，后连接信号避免过早触发）
    m_navigationList->setCurrentRow(0);
    
    // 连接信号（在设置完行之后连接，避免过早触发）
    connect(m_navigationList, &QListWidget::currentRowChanged, 
            this, &systemMain::onNavigationItemClicked);
    
    navLayout->addWidget(navTitle);
    navLayout->addWidget(m_navigationList);
    navLayout->addStretch();
}

QWidget* systemMain::createWelcomePage()
{
    QWidget *welcomeWidget = new QWidget(this);
    welcomeWidget->setObjectName("welcomePage");
    
    QVBoxLayout *layout = new QVBoxLayout(welcomeWidget);
    layout->setAlignment(Qt::AlignCenter);
    layout->setSpacing(30);
    
    // 欢迎标题
    QLabel *titleLabel = new QLabel("欢迎使用餐厅点餐系统", this);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setObjectName("welcomeTitle");
    
    // 副标题
    QLabel *subtitleLabel = new QLabel("请从左侧导航选择您需要的功能", this);
    subtitleLabel->setAlignment(Qt::AlignCenter);
    subtitleLabel->setObjectName("welcomeSubtitle");
    
    // 系统信息
    QLabel *infoLabel = new QLabel(
        "系统功能：\n"
        "• 菜单浏览和搜索\n"
        "• 购物车管理\n"
        "• 订单处理\n"
        "• 数据统计分析", this);
    infoLabel->setAlignment(Qt::AlignCenter);
    infoLabel->setObjectName("welcomeInfo");
    
    layout->addWidget(titleLabel);
    layout->addWidget(subtitleLabel);
    layout->addWidget(infoLabel);
    layout->addStretch();
    
    return welcomeWidget;
}

void systemMain::applyStyleSheet()
{
    setStyleSheet(R"(
        QMainWindow {
            background-color: #f5f5f5;
            font-family: "DejaVu Sans", "SimSun", "Microsoft YaHei";
        }
        
        QMenuBar {
            background-color: #34495e;
            color: white;
            border: none;
        }
        
        QMenuBar::item {
            background-color: transparent;
            padding: 5px 10px;
        }
        
        QMenuBar::item:selected {
            background-color: #2c3e50;
        }
        
        QToolBar {
            background-color: #ecf0f1;
            border: 1px solid #bdc3c7;
            spacing: 3px;
        }
        
        QStatusBar {
            background-color: #ecf0f1;
            border-top: 1px solid #bdc3c7;
        }
        
        #navigationList {
            background-color: white;
            border: 1px solid #bdc3c7;
            border-radius: 5px;
            font-size: 13px;
        }
        
        #navigationList::item {
            padding: 16px 12px; /* 增加垂直内边距 */
            border-bottom: 1px solid #ecf0f1;
            margin: 2px 0px; /* 增加外边距 */
            min-height: 20px; /* 设置最小高度 */
        }
        
        #navigationList::item:selected {
            background-color: #3498db;
            color: white;
        }
        
        #navigationList::item:hover {
            background-color: #e8f4f8;
        }
        
        #navTitle {
            font-size: 16px;
            font-weight: bold;
            color: #2c3e50;
            padding: 10px;
        }
        
        #welcomePage {
            background-color: white;
            border: 1px solid #bdc3c7;
            border-radius: 5px;
        }
        
        #welcomeTitle {
            font-size: 22px;
            font-weight: bold;
            color: #2c3e50;
        }
        
        #welcomeSubtitle {
            font-size: 16px;
            color: #7f8c8d;
        }
        
        #welcomeInfo {
            font-size: 14px;
            color: #34495e;
            background-color: #ecf0f1;
            padding: 20px;
            border-radius: 5px;
            border-left: 4px solid #3498db;
        }
    )");
}

void systemMain::updateUIState()
{
    // 根据用户角色更新导航列表可见性和文本
    if (m_navigationList) {
        for (int i = 0; i < m_navigationList->count(); ++i) {
            QListWidgetItem *item = m_navigationList->item(i);
            if (!item) continue;
            
            bool visible = true;
            
            // 更新导航项文本 - 索引3 (个人中心/用户管理) 根据角色显示不同文本
            if (i == 3) {
                if (m_currentRole == LoginUI::UserRole::Admin) {
                    item->setText("* 用户管理");
                } else {
                    item->setText("* 个人中心");
                }
            }
            
            // 管理员功能只对管理员可见(索引>=4: 菜单管理、订单管理、用户评价、数据统计)
            if (i >= 4 && m_currentRole != LoginUI::UserRole::Admin) {
                visible = false;
            }
            
            // 顾客功能只对顾客可见(索引1,2: 菜单浏览、购物车)
            if ((i == 1 || i == 2) && m_currentRole != LoginUI::UserRole::Customer) {
                visible = false;
            }
            
            item->setHidden(!visible);
        }
    }
    
    // 如果当前模块对当前角色不可见，切换到欢迎页面
    int moduleIndex = static_cast<int>(m_currentModule);
    bool shouldSwitchToWelcome = false;
    
    // 管理员不能访问顾客模块(索引1,2)，顾客不能访问纯管理模块(索引>=4)
    if (m_currentRole == LoginUI::UserRole::Admin && (moduleIndex == 1 || moduleIndex == 2)) {
        shouldSwitchToWelcome = true;
    } else if (m_currentRole == LoginUI::UserRole::Customer && moduleIndex >= 4) {
        shouldSwitchToWelcome = true;
    }
    
    if (shouldSwitchToWelcome) {
        switchToModule(UIModule::Welcome);
    }
    
    // 刷新状态栏
    refreshStatusBar();
}

void systemMain::setupWindow()
{
    setWindowTitle("餐厅点餐系统");
    setMinimumSize(1024, 600);
    setMaximumSize(1024, 600); // 固定为1024*600分辨率
    resize(1024, 600);
    
    // 居中显示
    move(0, 0); // 左上角对齐，避免超出屏幕
}

void systemMain::recreateMenuAndToolBar()
{
    // 清除现有的菜单和工具栏
    if (menuBar()) {
        menuBar()->clear();
        menuBar()->show(); // 重新显示，会在createMenuBar中根据角色决定是否隐藏
    }
    
    if (m_mainToolBar) {
        removeToolBar(m_mainToolBar);
        delete m_mainToolBar;
        m_mainToolBar = nullptr;
    }
    
    // 清除顾客标题栏
    if (m_customerTitleBar) {
        m_customerTitleBar->hide();
        m_customerTitleBar->deleteLater();
        m_customerTitleBar = nullptr;
    }
    
    // 重新创建菜单栏和工具栏
    createMenuBar();
    createToolBar();
    
    // 为管理员界面显示导航面板，为顾客界面隐藏导航面板
    if (m_navigationPanel) {
        bool showNavPanel = (m_currentRole == LoginUI::UserRole::Admin);
        m_navigationPanel->setVisible(showNavPanel);
    }
}

void systemMain::createCustomerTitleBar()
{
    // 如果已经存在，先删除
    if (m_customerTitleBar) {
        delete m_customerTitleBar;
        m_customerTitleBar = nullptr;
    }
    
    // 创建标题栏
    m_customerTitleBar = new QWidget(this);
    m_customerTitleBar->setFixedHeight(60);
    m_customerTitleBar->setStyleSheet(
        "QWidget {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                 stop:0 #FF6B6B, stop:1 #4ECDC4);"
        "    border-bottom: 2px solid #2C3E50;"
        "}"
    );
    
    QHBoxLayout *titleLayout = new QHBoxLayout(m_customerTitleBar);
    titleLayout->setContentsMargins(20, 10, 20, 10);
    titleLayout->setSpacing(20);
    
    // 餐厅Logo和名称
    m_titleLogoLabel = new QLabel("🍽️ 美味餐厅", m_customerTitleBar);
    m_titleLogoLabel->setStyleSheet(
        "QLabel {"
        "    font-size: 22px;"
        "    font-weight: bold;"
        "    color: white;"
        "}"
    );
    
    // 导航按钮区域
    QHBoxLayout *navButtonLayout = new QHBoxLayout();
    navButtonLayout->setSpacing(10);
    
    QPushButton *menuButton = new QPushButton("🍽️ 菜单", m_customerTitleBar);
    QPushButton *cartButton = new QPushButton("🛒 购物车", m_customerTitleBar);
    
    QString navButtonStyle = 
        "QPushButton {"
        "    background-color: #E8E8E8;"  /* 半透明白色替换为灰白色 */
        "    color: #2C3E50;"
        "    border: none;"
        "    padding: 6px 12px;"
        "    border-radius: 15px;"
        "    font-size: 14px;"
        "    font-weight: bold;"
        "}"
        "QPushButton:hover {"
        "    background-color: #F5F5F5;"  /* 更亮的灰白色 */
        "}"
        "QPushButton:pressed {"
        "    background-color: #D0D0D0;"  /* 更暗的灰色 */
        "}";
    
    menuButton->setStyleSheet(navButtonStyle);
    cartButton->setStyleSheet(navButtonStyle);
    
    connect(menuButton, &QPushButton::clicked, this, [this]() { 
        switchToModule(UIModule::CustomerMenu); 
    });
    connect(cartButton, &QPushButton::clicked, this, [this]() { 
        switchToModule(UIModule::CustomerCart); 
    });
    
    QPushButton *userCenterButton = new QPushButton("个人中心", m_customerTitleBar);
    userCenterButton->setStyleSheet(navButtonStyle);
    
    connect(userCenterButton, &QPushButton::clicked, this, [this]() { 
        switchToModule(UIModule::UserCenter); 
    });
    
    navButtonLayout->addWidget(menuButton);
    navButtonLayout->addWidget(cartButton);
    navButtonLayout->addWidget(userCenterButton);
    
    // 欢迎信息
    m_welcomeLabel = new QLabel("", m_customerTitleBar);
    m_welcomeLabel->setStyleSheet(
        "QLabel {"
        "    font-size: 16px;"
        "    color: white;"
        "}"
    );
    
    // 登出按钮
    m_logoutButton = new QPushButton("登出", m_customerTitleBar);
    m_logoutButton->setStyleSheet(
        "QPushButton {"
        "    background-color: #F0F0F0;"  /* 浅灰白色 */
        "    color: #2C3E50;"
        "    border: none;"
        "    padding: 8px 16px;"
        "    border-radius: 20px;"
        "    font-size: 14px;"
        "    font-weight: bold;"
        "}"
        "QPushButton:hover {"
        "    background-color: #FFFFFF;"  /* 纯白色 */
        "}"
        "QPushButton:pressed {"
        "    background-color: #E0E0E0;"  /* 更深的灰色 */
        "}"
    );
    
    connect(m_logoutButton, &QPushButton::clicked, this, &systemMain::handleLogout);
    
    // 布局
    titleLayout->addWidget(m_titleLogoLabel);
    titleLayout->addLayout(navButtonLayout);
    titleLayout->addStretch();
    titleLayout->addWidget(m_welcomeLabel);
    titleLayout->addWidget(m_logoutButton);
    
    // 将标题栏设置为主窗口的顶部组件
    // 需要重新组织中央widget的布局
    reorganizeCentralWidgetForCustomer();
    
    // 更新欢迎信息
    updateCustomerWelcomeMessage();
}

void systemMain::updateCustomerWelcomeMessage()
{
    if (m_welcomeLabel && m_currentRole == LoginUI::UserRole::Customer) {
        QString welcomeMsg = QString("欢迎您，%1! 🎉").arg(m_currentUsername);
        m_welcomeLabel->setText(welcomeMsg);
    }
}

void systemMain::reorganizeCentralWidgetForCustomer()
{
    if (!m_customerTitleBar || !m_centralWidget) {
        return;
    }
    
    // 保存现有的内容
    QWidget *oldCentralWidget = m_centralWidget;
    QSplitter *splitter = m_mainSplitter;
    
    // 创建新的中央widget
    QWidget *newCentralWidget = new QWidget(this);
    setCentralWidget(newCentralWidget);
    
    // 创建垂直布局：标题栏在顶部，内容在下方
    QVBoxLayout *newMainLayout = new QVBoxLayout(newCentralWidget);
    newMainLayout->setContentsMargins(0, 0, 0, 0);
    newMainLayout->setSpacing(0);
    
    // 添加标题栏到顶部
    newMainLayout->addWidget(m_customerTitleBar);
    
    // 创建内容区域容器
    QWidget *contentWidget = new QWidget();
    m_mainLayout = new QHBoxLayout(contentWidget);
    m_mainLayout->setContentsMargins(5, 5, 5, 5);
    m_mainLayout->setSpacing(5);
    
    // 将分割器移动到新的布局中
    if (splitter) {
        m_mainLayout->addWidget(splitter);
        
        // 对于顾客界面，隐藏导航面板，让界面更简洁
        if (m_navigationPanel) {
            m_navigationPanel->setVisible(false);
        }
    }
    
    // 添加内容区域到垂直布局
    newMainLayout->addWidget(contentWidget, 1); // 占据剩余空间
    
    // 更新成员变量
    m_centralWidget = newCentralWidget;
    
    // 清理旧的布局（但不删除splitter，因为已经移动了）
    if (oldCentralWidget && oldCentralWidget != newCentralWidget) {
        oldCentralWidget->deleteLater();
    }
}

QWidget* systemMain::createUserCenterPage()
{
    // 创建用户个人中心主页面
    QWidget *userCenterPage = new QWidget(this);
    QVBoxLayout *mainLayout = new QVBoxLayout(userCenterPage);
    mainLayout->setContentsMargins(10, 10, 10, 10);
    mainLayout->setSpacing(10);
    
    // 创建标题
    QLabel *titleLabel = new QLabel("个人中心", userCenterPage);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet(
        "QLabel {"
        "    font-size: 18px;"
        "    font-weight: bold;"
        "    color: #2C3E50;"
        "    padding: 10px;"
        "    background-color: #ECF0F1;"
        "    border-radius: 8px;"
        "    margin-bottom: 10px;"
        "}"
    );
    mainLayout->addWidget(titleLabel);
    
    // 创建标签页控件
    QTabWidget *tabWidget = new QTabWidget(userCenterPage);
    tabWidget->setStyleSheet(
        "QTabWidget::pane {"
        "    border: 2px solid #BDC3C7;"
        "    border-radius: 8px;"
        "    background-color: white;"
        "}"
        "QTabBar::tab {"
        "    background-color: #ECF0F1;"
        "    color: #2C3E50;"
        "    border: 2px solid #BDC3C7;"
        "    border-bottom: none;"
        "    border-radius: 6px 6px 0px 0px;"
        "    padding: 8px 16px;"
        "    margin-right: 2px;"
        "    font-size: 13px;"
        "    font-weight: bold;"
        "}"
        "QTabBar::tab:selected {"
        "    background-color: white;"
        "    color: #3498DB;"
        "    border-color: #3498DB;"
        "}"
        "QTabBar::tab:hover {"
        "    background-color: #D5DBDB;"
        "}"
    );
    
    // 创建用户个人中心的三个组件
    m_userInfoWidget = new UserInfoWidget(userCenterPage);
    m_orderHistoryWidget = new OrderHistoryWidget(userCenterPage);
    m_ratingWidget = new RatingWidget(userCenterPage);
    // 移除个人设置组件
    // m_userSettingsWidget = new UserSettingsWidget(userCenterPage);
    
    // 添加标签页
    tabWidget->addTab(m_userInfoWidget, "个人信息");
    tabWidget->addTab(m_orderHistoryWidget, "订单历史");
    tabWidget->addTab(m_ratingWidget, "订单评价");
    // 移除个人设置标签页
    // tabWidget->addTab(m_userSettingsWidget, "个人设置");
    
    // 用户信息更新功能已移除
    
    connect(m_userInfoWidget, &UserInfoWidget::passwordChangeRequested,
            this, [this](const QString& oldPassword, const QString& newPassword) {
                AuthResult result = m_userManager->changePassword(m_currentUserId, oldPassword, newPassword);
                if (result == AuthResult::SUCCESS) {
                    m_userInfoWidget->onPasswordChanged();
                } else {
                    QString errorMsg = "密码修改失败";
                    if (result == AuthResult::INVALID_CREDENTIALS) {
                        errorMsg = "原密码错误";
                    } else if (result == AuthResult::WEAK_PASSWORD) {
                        errorMsg = "新密码强度不足";
                    }
                    m_userInfoWidget->onOperationError(errorMsg);
                }
            });
    
    // 连接订单历史组件的信号
    connect(m_orderHistoryWidget, &OrderHistoryWidget::reorderRequested,
            this, &systemMain::handleReorderRequest);
    
    // 移除个人设置组件的信号连接
    // connect(m_userSettingsWidget, &UserSettingsWidget::settingsUpdated, ...);
    // connect(m_userSettingsWidget, &UserSettingsWidget::dataClearRequested, ...);
    
    mainLayout->addWidget(tabWidget);
    
    return userCenterPage;
}

// ============================================================================
// 重新下单功能实现
// ============================================================================

void systemMain::handleReorderRequest(const Order& order)
{
    if (!m_reorderService || !m_customerCartPage) {
        QMessageBox::critical(this, "错误", "重新下单服务未初始化");
        return;
    }
    
    // 验证当前用户状态
    if (m_currentUserId.isEmpty()) {
        QMessageBox::warning(this, "提示", "请先登录");
        return;
    }
    
    // 连接重新下单完成信号（一次性连接）
    connect(m_reorderService, &ReorderService::reorderCompleted,
            this, &systemMain::handleReorderCompleted, Qt::UniqueConnection);
    
    // 使用ReorderService处理重新下单
    ReorderResult result = m_reorderService->processReorder(order, m_currentUserId);
    
    if (result.hasAnySuccess()) {
        // 将结果添加到购物车
        ReorderResult cartResult = m_customerCartPage->addItemsFromOrder(order.items);
        
        // 更新结果信息
        if (cartResult.isSuccess) {
            result.message = cartResult.message;
            result.totalAmount = cartResult.totalAmount;
        }
        
        // 切换到购物车页面
        switchToModule(UIModule::CustomerCart);
        
        // 显示操作结果
        handleReorderCompleted(result);
    } else {
        // 完全失败，显示错误信息
        QMessageBox::warning(this, "重新下单失败", result.message);
    }
}

void systemMain::handleReorderCompleted(const ReorderResult& result)
{
    QString title;
    QString message = result.generateUserMessage();
    
    if (result.isCompleteSuccess()) {
        title = "重新下单成功";
        QMessageBox::information(this, title, message);
    } else if (result.isPartialSuccess()) {
        title = "重新下单部分成功";
        
        // 创建详细的消息对话框
        QMessageBox msgBox(this);
        msgBox.setWindowTitle(title);
        msgBox.setText(message);
        
        if (!result.unavailableItems.isEmpty() || !result.insufficientItems.isEmpty()) {
            QString detailText = "详细信息：\n";
            
            if (!result.successItemsDetails.isEmpty()) {
                detailText += "\n✓ 成功添加的菜品：\n";
                for (const QString& item : result.successItemsDetails) {
                    detailText += QString("  • %1\n").arg(item);
                }
            }
            
            if (!result.unavailableItems.isEmpty()) {
                detailText += "\n✗ 不可用的菜品：\n";
                for (const QString& item : result.unavailableItems) {
                    detailText += QString("  • %1（已下架）\n").arg(item);
                }
            }
            
            if (!result.insufficientItems.isEmpty()) {
                detailText += "\n⚠ 库存不足的菜品：\n";
                for (const QString& item : result.insufficientItems) {
                    detailText += QString("  • %1（库存不足）\n").arg(item);
                }
            }
            
            msgBox.setDetailedText(detailText);
        }
        
        msgBox.setIcon(QMessageBox::Information);
        msgBox.exec();
    } else {
        title = "重新下单失败";
        QMessageBox::warning(this, title, message);
    }
    
    // 更新状态栏
    if (result.hasAnySuccess()) {
        statusBar()->showMessage(QString("重新下单完成：成功添加 %1 个菜品，总金额 ¥%2")
                                .arg(result.successItems + result.partialItems)
                                .arg(result.totalAmount, 0, 'f', 2), 5000);
    }
}

QWidget* systemMain::createAdminStatsPage()
{
    QWidget* statsPage = new QWidget();
    QVBoxLayout* mainLayout = new QVBoxLayout(statsPage);
    mainLayout->setContentsMargins(20, 20, 20, 20);
    mainLayout->setSpacing(15);
    
    // 页面标题
    QLabel* titleLabel = new QLabel("数据统计分析", statsPage);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("QLabel { font-size: 20px; font-weight: bold; padding: 15px; background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #e3f2fd, stop:1 #bbdefb); border-radius: 8px; color: #1565c0; }");
    
    // 创建滚动区域
    QScrollArea* scrollArea = new QScrollArea(statsPage);
    scrollArea->setWidgetResizable(true);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    scrollArea->setFrameShape(QFrame::NoFrame);
    
    QWidget* scrollContent = new QWidget();
    QVBoxLayout* scrollLayout = new QVBoxLayout(scrollContent);
    scrollLayout->setContentsMargins(10, 10, 10, 10);
    scrollLayout->setSpacing(15);

    // 创建实时统计组件
    m_orderStatisticsWidget = new OrderStatisticsWidget(scrollContent);
    m_orderStatisticsWidget->setTodayFocus(true);
    
    // 延迟获取统计数据，避免在初始化时获取锁导致死锁
    QTimer::singleShot(200, this, [this]() {
        if (m_orderManager && m_orderStatisticsWidget) {
            try {
                OrderStatistics currentStats = m_orderManager->getTodayStatistics();
                m_orderStatisticsWidget->updateStatistics(currentStats);
            } catch (const std::exception& e) {
                // 使用默认统计数据
                OrderStatistics defaultStats;
                m_orderStatisticsWidget->updateStatistics(defaultStats);
            }
        }
    });
    
    // 连接订单管理器信号到统计组件，实现实时更新
    connect(m_orderManager, &OrderManager::orderCreated, this, [this](const Order&) {
        updateStatisticsDisplay();
    });
    connect(m_orderManager, &OrderManager::orderStatusUpdated, this, [this](const QString&, OrderStatus, OrderStatus) {
        updateStatisticsDisplay();
    });
    connect(m_orderManager, &OrderManager::orderCompleted, this, [this](const QString&) {
        updateStatisticsDisplay();
    });
    connect(m_orderManager, &OrderManager::orderCancelled, this, [this](const QString&, const QString&) {
        updateStatisticsDisplay();
    });
    connect(m_orderManager, &OrderManager::ordersChanged, this, [this]() {
        updateStatisticsDisplay();
    });
    
    // 延迟连接DataManager的外部文件变更信号，避免初始化冲突
    QTimer::singleShot(100, this, [this]() {
        connect(&DataManager::instance(), &DataManager::externalFileChanged, this, [this](DataType dataType, const QString&) {
            if (dataType == DataType::ORDERS && m_orderStatisticsWidget) {
                // 延迟更新，确保文件写入完成
                QTimer::singleShot(100, this, [this]() {
                    updateStatisticsDisplay();
                });
            }
        });
    });
    
    // 历史统计详细信息区域
    QGroupBox* detailedStatsGroup = new QGroupBox("详细统计信息", scrollContent);
    QVBoxLayout* detailedLayout = new QVBoxLayout(detailedStatsGroup);
    detailedLayout->setSpacing(8);
    
    // 创建详细统计标签（这些会通过信号槽机制更新）
    QLabel* todayDetailLabel = new QLabel("正在加载今日详细统计...", detailedStatsGroup);
    QLabel* allTimeDetailLabel = new QLabel("正在加载历史详细统计...", detailedStatsGroup);
    
    todayDetailLabel->setObjectName("todayDetailLabel");
    allTimeDetailLabel->setObjectName("allTimeDetailLabel");
    
    QString detailLabelStyle = R"(
        QLabel {
            padding: 12px;
            background-color: #f5f5f5;
            border: 1px solid #ddd;
            border-radius: 6px;
            color: #333;
            font-size: 12px;
            line-height: 1.4;
        }
    )";
    
    todayDetailLabel->setStyleSheet(detailLabelStyle);
    allTimeDetailLabel->setStyleSheet(detailLabelStyle);
    todayDetailLabel->setWordWrap(true);
    allTimeDetailLabel->setWordWrap(true);
    
    detailedLayout->addWidget(todayDetailLabel);
    detailedLayout->addWidget(allTimeDetailLabel);
    
    // 添加手动刷新按钮
    QPushButton* refreshButton = new QPushButton("立即刷新统计数据", scrollContent);
    refreshButton->setStyleSheet(R"(
        QPushButton {
            background-color: #2196f3;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            font-weight: bold;
            font-size: 13px;
        }
        QPushButton:hover {
            background-color: #1976d2;
        }
        QPushButton:pressed {
            background-color: #0d47a1;
        }
    )");
    
    // 连接手动刷新按钮
    connect(refreshButton, &QPushButton::clicked, this, [this]() {
        updateStatisticsDisplay();
        
        // 显示刷新成功提示
        if (m_statusLabel) {
            m_statusLabel->setText("统计数据已刷新");
            QTimer::singleShot(3000, this, [this]() {
                refreshStatusBar(); // 恢复正常状态显示
            });
        }
    });
    
    // 组装布局
    scrollLayout->addWidget(m_orderStatisticsWidget);
    scrollLayout->addWidget(detailedStatsGroup);
    scrollLayout->addWidget(refreshButton);
    scrollLayout->addStretch();
    
    scrollArea->setWidget(scrollContent);
    
    mainLayout->addWidget(titleLabel);
    mainLayout->addWidget(scrollArea);
    
    // 初次更新详细统计信息
    updateStatisticsDisplay();
    
    return statsPage;
}

void systemMain::updateStatisticsDisplay()
{
    if (!m_orderStatisticsWidget || !m_orderManager) {
        return;
    }
    
    try {
        // 更新实时统计组件
        OrderStatistics currentStats = m_orderManager->getTodayStatistics();
        m_orderStatisticsWidget->updateStatistics(currentStats);
        
        // 查找并更新详细统计标签
        if (m_adminStatsPage) {
            QLabel* todayDetailLabel = m_adminStatsPage->findChild<QLabel*>("todayDetailLabel");
            QLabel* allTimeDetailLabel = m_adminStatsPage->findChild<QLabel*>("allTimeDetailLabel");
            
            if (todayDetailLabel) {
                // 获取今日详细统计
                OrderStatistics todayStats = m_orderManager->getTodayStatistics();
                double todayCompletionRate = (todayStats.totalOrders > 0) ? 
                    (double)todayStats.completedOrders / todayStats.totalOrders * 100 : 0;
                
                QString todayText = QString(
                    "📊 今日统计详情\n"
                    "• 订单总数: %1 单\n"
                    "• 已完成: %2 单 (%3%)\n"
                    "• 制作中: %4 单\n"
                    "• 待处理: %5 单\n"
                    "• 已取消: %6 单\n"
                    "• 营业额: ¥%7\n"
                    "• 平均单价: ¥%8"
                ).arg(todayStats.totalOrders)
                 .arg(todayStats.completedOrders)
                 .arg(todayCompletionRate, 0, 'f', 1)
                 .arg(todayStats.preparingOrders)
                 .arg(todayStats.pendingOrders)
                 .arg(todayStats.cancelledOrders)
                 .arg(todayStats.totalRevenue, 0, 'f', 2)
                 .arg(todayStats.averageOrderValue, 0, 'f', 2);
                
                todayDetailLabel->setText(todayText);
            }
            
            if (allTimeDetailLabel) {
                // 获取历史详细统计
                OrderStatistics allTimeStats = m_orderManager->getOrderStatistics();
                double allTimeCompletionRate = (allTimeStats.totalOrders > 0) ? 
                    (double)allTimeStats.completedOrders / allTimeStats.totalOrders * 100 : 0;
                
                QString allTimeText = QString(
                    "📈 历史统计详情\n"
                    "• 订单总数: %1 单\n"
                    "• 已完成: %2 单 (%3%)\n"
                    "• 制作中: %4 单\n"
                    "• 待处理: %5 单\n"
                    "• 已取消: %6 单\n"
                    "• 总营业额: ¥%7\n"
                    "• 平均单价: ¥%8"
                ).arg(allTimeStats.totalOrders)
                 .arg(allTimeStats.completedOrders)
                 .arg(allTimeCompletionRate, 0, 'f', 1)
                 .arg(allTimeStats.preparingOrders)
                 .arg(allTimeStats.pendingOrders)
                 .arg(allTimeStats.cancelledOrders)
                 .arg(allTimeStats.totalRevenue, 0, 'f', 2)
                 .arg(allTimeStats.averageOrderValue, 0, 'f', 2);
                
                allTimeDetailLabel->setText(allTimeText);
            }
        }
        
    } catch (const std::exception& e) {
        // 如果更新失败，使用默认数据
        OrderStatistics defaultStats;
        m_orderStatisticsWidget->updateStatistics(defaultStats);
    }
}

void systemMain::setupFonts()
{
    
    // 尝试设置一个安全的字体，支持中文显示
    QFont appFont;
    
    // 按优先级尝试不同的字体
    QStringList fontNames = {
        "DejaVu Sans",      // 通常在Linux上可用
        "Liberation Sans",   // 另一个常见的Linux字体
        "Arial",            // 如果有的话
        "Sans Serif"        // 系统默认无衬线字体
    };
    
    bool fontSet = false;
    for (const QString& fontName : fontNames) {
        QFont testFont(fontName);
        if (QFontInfo(testFont).family() == fontName) {
            appFont = testFont;
            appFont.setPointSize(10);
            fontSet = true;
            break;
        }
    }
    
    if (!fontSet) {
        // 如果都不可用，使用系统默认字体
        appFont = QApplication::font();
    }
    
    // 为整个应用程序设置字体
    QApplication::setFont(appFont);
}

// ============================================================================
// 用户界面智能路由方法
// ============================================================================

void systemMain::showUserManagementInterface()
{
    // 管理员显示用户管理界面
    if (!m_contentStack || !m_userManagementWidget) {
        return;
    }
    
    // 如果用户管理界面还没有添加到堆栈中，需要创建一个临时容器
    // 在当前设计中，我们将用户管理界面显示在UserCenter的位置
    QWidget* currentUserCenterWidget = m_contentStack->widget(static_cast<int>(UIModule::UserCenter));
    
    // 临时替换UserCenter位置的widget
    m_contentStack->removeWidget(currentUserCenterWidget);
    m_contentStack->insertWidget(static_cast<int>(UIModule::UserCenter), m_userManagementWidget);
    
    // 切换到用户管理界面
    m_contentStack->setCurrentIndex(static_cast<int>(UIModule::UserCenter));
}

void systemMain::showUserCenterInterface()
{
    // 顾客显示个人中心界面
    if (!m_contentStack || !m_userCenterPage) {
        return;
    }
    
    // 确保UserCenter位置显示的是个人中心页面
    QWidget* currentWidget = m_contentStack->widget(static_cast<int>(UIModule::UserCenter));
    
    if (currentWidget != m_userCenterPage) {
        // 如果当前显示的不是个人中心页面，需要替换回来
        m_contentStack->removeWidget(currentWidget);
        m_contentStack->insertWidget(static_cast<int>(UIModule::UserCenter), m_userCenterPage);
    }
    
    // 切换到个人中心界面
    m_contentStack->setCurrentIndex(static_cast<int>(UIModule::UserCenter));
}
